package tp.pr1;

import java.util.Scanner;

public class RobotEngine {
	private Place actualPlace;
	private Direction actualDirection;
	private Street[] streets;
	
	public RobotEngine(Place initialPlace,
	           Direction direction,
	           Street[] cityMap)
	{
	 actualPlace=initialPlace;
	 actualDirection=direction;
	 streets=cityMap;
	}
	
	public void startEngine()
	{
		String LINE_SEPARATOR = System.getProperty("line.separator");
		Instruction instruction = new Instruction();
		Interpreter interpreter = new Interpreter();
		Scanner sc=new Scanner(System.in);
		System.out.println(actualPlace.toString());	
		System.out.println("WALL·E is looking at direction " + actualDirection.toString());	
		
		while(!actualPlace.isSpaceship() && instruction.getAction()!=Action.QUIT)
		{					  
		 System.out.print(LINE_SEPARATOR);
		 System.out.print("WALL·E > ");		 
		 String order =sc.nextLine();
		 instruction=interpreter.generateInstruction(order);
		 
		 if(instruction.isValid())
		 	{
			 switch(instruction.getAction())
				 {
				 case HELP: System.out.println(interpreter.interpreterHelp());break;
				 case QUIT: System.out.println("WALL·E says: I have communication problems. Bye bye");break;
				 case TURN: 
					       {
					    	 actualDirection=Direction.rotate(actualDirection,instruction.getRotation());		
					    	 System.out.println("WALL·E is looking at direction " + actualDirection.toString());	
					       };break;
				 case MOVE: this.changePlace();break;
				 default:break;
				 }
		 	}
		 else
		 	{
			 System.out.println("WALL·E says: I do not understand. Please repeat");
		 	}
		if(actualPlace.isSpaceship())System.out.println("WALL·E says: I am at my spaceship. Shutting down... Bye bye");
		}
	sc.close();	
   }	
	


private void changePlace()
	{
	 boolean finded=false;
	 	 for(int i=0;i<streets.length && !finded;i++)
	  	{
		  if(streets[i].comeOutFrom(actualPlace,actualDirection))
			  {
			  actualPlace=streets[i].nextPlace(actualPlace);
			  System.out.println("WALL·E says: Moving in direction " + actualDirection.toString());
			  System.out.println(actualPlace.toString());
			  if(!actualPlace.isSpaceship()) System.out.println("WALL·E is looking at direction " + actualDirection.toString());	
			  finded=true;
			  }		  
	  	}
	 if(!finded)System.out.println("WALL·E says: There is no street in direction " + actualDirection.toString()); 
	 	 
	}	
}

	
